
/**
 * [ossUpload oss直传]
 * @param  {Object} config          [配置host,accessid,accesskey]
 * @param  {[type]} select_dom      [选择文件触发按钮dom对象]
 * @param  {[type]} upload_dom      [上传触发按钮dom对象]
 * @param  {[type]} oss_file_dom    [存放准备上传的dom]
 * @param  {Array}  mime_types      [文件类型限制]
 * @param  {String} file_name       [上传路径]
 * @param  {String} callback        [上传完成之后回调函数]
 * @return {[type]}                 [description]
 */
function ossUpload (config = {} , mime_types = [] , file_name = '' , select_dom = null , upload_dom = null , oss_file_dom = null,callback) {
    var time = Date.parse(new Date());
    file_name = file_name == '' ?  'uploads/file/'+time+'.pdf' :  file_name;

    if(select_dom == null) {
        alert('select_dom lose');
        return;
    }

    if(upload_dom == null) {
        alert('upload_dom lose');
        return;
    }

    if(oss_file_dom == null) {
        oss_file_dom = select_dom.parentNode.previousElementSibling;
      
    }
    var policyText = {
        "expiration": "2020-01-01T12:00:00.000Z", //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
        "conditions": [
        ["content-length-range", 0, 1048576000] // 设置上传文件的大小限制
        ]
    };

    var policyBase64 = Base64.encode(JSON.stringify(policyText))
    message = policyBase64
    var bytes = Crypto.HMAC(Crypto.SHA1, message, config.accesskey, { asBytes: true }) ;
    var signature = Crypto.util.bytesToBase64(bytes);
    var uploader = new plupload.Uploader({
        runtimes : 'html5,flash,silverlight,html4',
        filters:{
            mime_types :mime_types,
        },
        browse_button : select_dom, 
        //runtimes : 'flash',
        container: select_dom.parentNode,
        flash_swf_url : 'lib/plupload-2.1.2/js/Moxie.swf',
        silverlight_xap_url : 'lib/plupload-2.1.2/js/Moxie.xap',
        
        url : config.host,
        multi_selection:false,  //不允许多文件上传
        multipart_params: {
            'Filename': file_name, 
            'key':file_name, 
            'policy': policyBase64,
            'OSSAccessKeyId': config.accessid, 
            'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
            'signature': signature,
        },

        init: {
            PostInit: function() {
                oss_file_dom.innerHTML = '';
                upload_dom.onclick = function() {
                    uploader.start();
                    return false;
                };
            },

            FilesAdded: function(up, files) {
                if(up.files.length > 1) {
                    uploader.removeFile(up.files[0].id);
                }
          
                plupload.each(files, function(file) {
                    oss_file_dom.innerHTML = '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ')<b></b>'
                    +'<div class="progress"><div class="progress-bar" style="width: 0%"></div></div>'
                    +'</div>';
                });
            },
       
           
            UploadProgress: function(up, file) {
              
                var d = document.getElementById(file.id);
                d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
                
                var prog = d.getElementsByTagName('div')[0];
                var progBar = prog.getElementsByTagName('div')[0]
                progBar.style.width= 2*file.percent+'px';
                progBar.setAttribute('aria-valuenow', file.percent);
            },
           
            FileUploaded:callback,

            Error: function(up, err) {
                document.getElementById('console').appendChild(document.createTextNode("\nError xml:" + err.message));
            }
        }
    });

    uploader.init();
}

/*function getRndInteger(min, max) {
  return Math.floor(Math.random() * (max - min + 1) ) + min;
}

var time = Date.parse(new Date())+''+getRndInteger(10000,99999);

var file_name =  'uploads/file/'+time+'.pdf' ;
ossUpload(
    {accessid:'{$Think.config.ali.accessid}',accesskey:'{$Think.config.ali.accesskey}',host:'{$Think.config.ali.host}'},
     [{ title:'Pdf file',extensions:'pdf'}],
    file_name,
    document.querySelectorAll('.selectfiles')[0],
    document.querySelectorAll('.postfiles')[0],
    null,
    function(up, file, info) {
        if (info.status >= 200 || info.status < 200){
            document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = 'success';
            $('input[name=ossurl]').val('{$Think.config.ali.host}/'+file_name);
        }else{
            document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = info.response;
        } 
    }
);
*/

